<template>
	<view :style="{ minHeight: sys.windowHeight + 'px' }"
		:class="[$tm.vx.state().tmVuetify.black ? 'black' : 'grey text ']">
		<tm-menubars color="primary" title="记账泡" :shadow="0">
			<template #left>
				<view class="pl-24">
					<tm-row>
						<tm-col :grid="6">
							<tm-images @click="sao" :previmage="false" :width="38" src="static/sao.png"></tm-images>
						</tm-col>
						<tm-col :grid="6">
							<tm-images @click="upload" :previmage="false" :width="38" src="static/upload.png">
							</tm-images>
						</tm-col>
					</tm-row>
				</view>
			</template>
		</tm-menubars>
		<view>
			<view class="fixed fulled  overflow" style="z-index: 8;">
				<tm-tabs :fllowTheme="false" bg-color="orange" color="yellow" @change="change" v-model="activeIndex"
					:list="list" range-key="title"></tm-tabs>
			</view>
			<view style="height: 84rpx;"></view>
		</view>

		<view :class="[$tm.vx.state().tmVuetify.black ? 'black' : $tm.vx.state().tmVuetify.color || 'primary']">
			<view class=" py-32" style=""
				:class="[$tm.vx.state().tmVuetify.black ? 'grey-darken-5 bk' : $tm.vx.state().tmVuetify.color || 'primary']">
				<view class="text-size-s text-align-center text-white">
					<tm-pickersDate @confirm="selectTime" :default-value="time" @input="changeValue">
						<text>{{ time }}</text>
					</tm-pickersDate>
					<tm-pickers @confirm="selectBook" :default-value="selected" rang-key="name" @input="changeValue"
						btn-color="bg-gradient-yellow-lighten" :list="bookList">
						<tm-button size="m" theme="bg-gradient-orange-accent">{{ book.name }}</tm-button>
					</tm-pickers>
				</view>
			</view>
			<view class="pt-14 pb-n10 round-t-8" :class="[$tm.vx.state().tmVuetify.black ? 'black' : 'grey text  ']">
				<!-- //内容 -->
				<tm-sheet color="orange">
					<view class="text-size-s text-weight-b ">
						<tm-input @click="open" v-model="word" disabled input-type="digit" :title="type.text"
							align="right" suffix="元" :border-bottom="false" :left-icon="type.icon"></tm-input>
						<tm-divider></tm-divider>
						<tm-input align="right" v-model="remarks" left-icon="icon-comment-lines" title="备注"
							@focus="show =false" confirm-type="search" @confirm="show = true" :round="0"></tm-input>
					</view>
				</tm-sheet>
				<tm-grid :grid="5" @change="selectType" color="orange" :list="types"></tm-grid>
			</view>
		</view>
		<tm-keyborad @confirm="confirm" model="number" :show.sync="show" v-model="word"></tm-keyborad>
		<tm-message ref="toast"></tm-message>
	</view>
</template>

<script>
	// https://roundicons.com/icon-packs/free-christmas-icons/
	import tmMenubars from '@/tm-vuetify/components/tm-menubars/tm-menubars.vue';
	import tmTabs from "@/tm-vuetify/components/tm-tabs/tm-tabs.vue"
	import tmSheet from "@/tm-vuetify/components/tm-sheet/tm-sheet.vue"
	import tmGrid from "@/tm-vuetify/components/tm-grid/tm-grid.vue"
	import tmIcons from '@/tm-vuetify/components/tm-icons/tm-icons.vue';
	import tmInput from "@/tm-vuetify/components/tm-input/tm-input.vue"
	import tmKeyborad from "@/tm-vuetify/components/tm-keyborad/tm-keyborad.vue"
	import tmPickersDate from "@/tm-vuetify/components/tm-pickersDate/tm-pickersDate.vue"
	import tmPickers from '@/tm-vuetify/components/tm-pickers/tm-pickers.vue';
	import tmImages from "@/tm-vuetify/components/tm-images/tm-images.vue"

	import tmCol from "@/tm-vuetify/components/tm-col/tm-col.vue"
	import tmRow from "@/tm-vuetify/components/tm-row/tm-row.vue"
	import tmMessage from "@/tm-vuetify/components/tm-message/tm-message.vue"


	export default {
		components: {
			tmImages,
			tmTabs,
			tmMenubars,
			tmGrid,
			tmSheet,
			tmIcons,
			tmInput,
			tmKeyborad,
			tmPickersDate,
			tmPickers,
			tmRow,
			tmCol,
			tmMessage
		},
		data() {
			return {
				mask: false,
				time: '2021/12/13',
				list: ['支出', '收入'],
				activeIndex: 0,
				show: false,
				word: '',
				type: {},
				er: 0,
				types: [],
				id: '',
				bill: null,
				selected: [],
				bookList: [],
				book: {},
				remarks: ''
			};
		},
		created() {
			this.sys = uni.getSystemInfoSync();
			// #ifdef H5
			this.bottom = 55
			// #endif

		},
		onLoad() {
			// #ifdef MP
			this.top = uni.upx2px(150);
			// #endif
		},
		onShow() {
			this.judgeLogin(() => {
				let bill = uni.getStorageSync('billId');
				uni.removeStorageSync('billId')
				if (null != bill && undefined != bill && '' != bill) {
					this.bill = bill
					this.er = bill.er;
					this.remarks = bill.remarks;
					this.id = bill.id;
					this.word = bill.value + "";
					this.time = bill.time
					this.activeIndex = bill.er;
				} else {
					this.getCurrentTime()
					this.bill = null
					this.er = 0;
					this.id = '';
					this.remarks = '';
					this.word = "";
					this.activeIndex = 0
				}
				this.loadType();
			});
			this.loadBook();
		},
		onHide() {
			this.bill = null
		},
		mounted() {
			this.judgeLogin(() => {
				this.getCurrentTime()
				this.loadType()
			});
			this.loadBook();
		},
		methods: {
			sao() {
				let that = this;
				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						let bid = res.result;
						if (null != bid && '' != bid) {
							that.$ajax.get('/book/shareRecive/' + bid).then(re => {
								let b = re.data
								uni.showModal({
									title: '提示',
									content: '确认接收' + b.uid + '的共享账本:' + b.name,
									success: function(res) {
										if (res.confirm) {
											that.judgeLogin(ee => {
												that.$ajax.post(
													'/book/shareConfirm', {
														id: bid,
														uid: ee.id
													}).then(ree => {
													if (ree.code == 1) {
														uni.$tm.toast(
															'接收成功');
													}
												})
											})
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							})
						}
					}
				});
			},
			loadBook() {
				this.judgeLogin((res) => {
					this.$ajax.post('/book/list', {
						uid: res.id
					}).then(res => {
						let ch = 0;
						this.bookList = res.data;
						if (this.bill && this.bill.bid) {
							let tag = true;
							for (let i in this.bookList) {
								if (this.bookList[i].id == this.bill.bid) {
									this.book = this.bookList[i];
									tag = false;
									ch = i;
									break;
								}
							}
							if (tag) {
								this.book = this.bookList[0];
							}
						} else {
							this.book = this.bookList[0];
						}
						this.selected = [ch]
					})
				})
			},
			selectBook(val) {
				console.log(val)
				this.book = val[0].data
				this.selected = [val[0].index]
			},
			changeValue(val) {
				if (this.show) {
					this.show = false;
				}
			},
			loadType() {
				this.$ajax.get('/type/load/' + this.er).then(res => {
					this.types = res.data
					if (this.bill && this.bill.type) {
						let tag = true;
						this.types.forEach(i => {
							if (i.id == this.bill.type) {
								this.type = i;
								tag = false;
							}
						})
						if (tag) {
							this.type = this.types[0];
						}
					} else {
						this.type = this.types[0];
					}
				})
			},
			selectType(e) {
				this.type = e.data
			},
			closeKey() {
				this.show = false;
			},
			open() {
				this.show = true;
			},
			selectTime(e) {
				this.time = e.year + "/" + e.month + "/" + e.day
			},
			getCurrentTime() {
				//获取当前时间并打印
				let yy = new Date().getFullYear();
				let mm = new Date().getMonth() + 1;
				let dd = new Date().getDate();
				let hh = new Date().getHours();
				let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
				let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
				this.time = yy + '/' + mm + '/' + dd;
			},
			change(e) {
				this.type = {}
				this.er = e
				this.loadType()
			},
			afterLoadType() {
				this.$ajax.get('/type/load/' + this.er).then(res => {
					this.types = res.data
					this.type = this.types[0];
				})

			},
			confirm(val) {
				this.show = true;
				if (val <= 0) {
					uni.$tm.toast('金额无效');
					return;
				}
				this.judgeLogin((res) => {
					this.$ajax.post('/bill/save', {
						type: this.type.id,
						er: this.er,
						value: val,
						uid: res.id,
						id: this.id,
						time: this.time,
						bid: this.book.id,
						remarks: this.remarks
					}).then(res => {
						if (res.code == 1) {
							uni.$tm.toast('记账成功');
							this.word = ''
							this.remarks = '';
							this.id = ''
							// this.type = {}
						} else {
							uni.$tm.toast('记账失败');
						}
					})
				});

			},
			upload() {
				let that = this;
				uni.chooseImage({
					count: 1, //上传图片的数量，默认是9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						const tempFilePaths = res.tempFilePaths;
						that.$refs.toast.show({
							model: 'load',
							mask: true
						})
						uni.uploadFile({
							url: 'http://127.0.0.1/bill/bill/file', //post请求的地址
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								'token': uni.getStorageSync("userInfo").token
							},
							success: (uploadFileRes) => {
								that.$refs.toast.hide()
								//这里要注意，uploadFileRes.data是个String类型，要转对象的话需要JSON.parse一下
								var obj = JSON.parse(uploadFileRes.data);
								uni.navigateTo({
									url: '/pages/index/images?id=' + obj.data,
								});
							},
							fail: () => {
								that.$refs.toast.hide()
							}
						})
					},
					fail: () => {
						that.$refs.toast.hide()
					}
				});

			},
			openUrl(url) {
				let t = this;
				uni.navigateTo({
					url: url,
					fail: e => {}
				});
			},
		}
	};
</script>

<style lang="scss">
	page,
	body {
		min-height: 100%;
		background-color: #f5f5f5;
	}
</style>
<style lang="scss" scoped></style>
